import os
import re
import time
import logging
from logging.handlers import TimedRotatingFileHandler
from util.TimeUtil    import *

from util.Config import *

class LoggerUtil:

    def __init__(self, model):
        try:
            logging.shutdown()
            # 获取logger对象,取名mylog
            self.logger = logging.getLogger(model)
            # 移除根日志记录器的处理程序
            self.logger.handlers = []
            # 输出DEBUG及以上级别的信息，针对所有输出的第一层过滤
            self.logger.setLevel(level=logging.DEBUG)

            # 日志路径
            LogPath = Config["Sys"]["logPath"] + getYYYYMM() + "/"
            if not os.path.exists(LogPath):
                os.makedirs(LogPath)

            # 获取文件日志句柄并设置日志级别，第二层过滤  midnight
            handler = TimedRotatingFileHandler(filename=LogPath + "fieldiag.log", when="midnight", interval=1, backupCount=180, encoding='utf-8')  # encoding="utf-8"
            handler.setLevel(logging.INFO)

            # # 按秒分隔   好使M
            # handler.suffix = "%Y%m%d%H%M%S"
            # handler.extMatch = re.compile('^\\d{14}(\\.\\w+)?$', re.ASCII)

            # 按天分隔
            handler.suffix = "%Y%m%d"
            extMatch = r"^\d{8}(\.\w+)?$"
            handler.extMatch = re.compile(extMatch, re.ASCII)

            # 生成并设置文件日志格式，其中name为上面设置的 model
            # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            Account = Config["Sys"]["AccountName"]
            if Account == None:
                Account = '未登录'
            formatter = logging.Formatter('%(asctime)s - %(name)s - [%(filename)s -->line:%(lineno)d] - %(levelname)s:['+Account+']--> %(message)s', datefmt='%H:%M:%S')
            handler.setFormatter(formatter)

            # 获取流句柄并设置日志级别，第二层过滤
            console = logging.StreamHandler()
            console.setLevel(logging.DEBUG)

            # 为logger对象添加句柄
            self.logger.addHandler(handler)
            self.logger.addHandler(console)
        except Exception as e:
            print("Logger Error: >>> ", e)
        
if __name__ == "__main__":
    print('logger...')
    # logger = LoggerUtil('sku').logger

    # logger.info("show info")
    # logger.debug("show debug")
    # logger.warning("show warning")
    # logger.error("show error 啊啊啊")

        
    while True:
         
        logger = LoggerUtil('test').logger

        logger.info('=================')

        time.sleep(1)

